<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/11/4
 * Time: 16:45
 */

use App\Models\Certification;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use App\Models\Setting;
use App\Models\ErrorLog;
use App\Models\FareOrder;
use App\Models\User;
use App\Models\IncomeRecord;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Faceid\V20180301\FaceidClient;
use TencentCloud\Faceid\V20180301\Models\PhoneVerificationRequest;
use Illuminate\Support\Str;
use Tencent\TLSSigAPIv2;
use App\Libraries\TencentIm;
use App\Models\AgentProfit;
use App\Models\VipUser;
use App\Models\Attention;
use App\Models\Broker;
use App\Models\BrokerLevel;
use App\Models\Level;

/**
 * 获取不常变动的公共参数
 */
if (!function_exists('getSetting')) {
    function getSetting($key = '')
    {
        $info = Cache::get('systemConfig');
        $info = null;
        if (!$info) {
            $info = Setting::pluck('value', 'key');
            Cache::put('systemConfig', $info);
        }
        return $key ? $info[$key] : $info;
    }
}

if (!function_exists('defaultPlat')) {
    function defaultPlat($user_id)
    {
        $key = 'uid:' . $user_id . ':plat';
        $plat = Redis::get($key);
        if (empty($plat)) {
            return 1;
        } else {
            Redis::set($key, $plat);
            return $plat;
        }
    }
}

/**
 * redis锁，3秒自动解锁
 */
if (!function_exists('redisLock')) {
    function redisLock($key = '', $ttl = 3)
    {
        if (!Redis::setnx($key, 1)) {
            if (Redis::ttl($key) == -1) {
                Redis::expire($key, $ttl);
            }
            return false;
        } else {
            Redis::expire($key, $ttl);
        }
        return true;
    }
}

/**
 * redis解锁
 */
if (!function_exists('redisUnlock')) {
    function redisUnlock($key = '')
    {
        Redis::del($key);
    }
}

/**
 * 记录异常
 */
if (!function_exists('errorLog')) {
    function errorLog($uid = 0, $title = '', $info = '')
    {
        ErrorLog::create([
            'user_id' => $uid,
            'title' => $title,
            'info' => $info,
        ]);
    }
}

/**
 * 短信验证码验证
 */
if (!function_exists('smsCheck')) {
    function smsCheck($phone, $code, $sms_key)
    {
        //万能验证码
        if($code == 6688){
            Cache::forget($sms_key);
            return ['code' => 200, 'msg' => 'success'];
        }
        $smsData = Cache::get($sms_key);
        if (empty($smsData)) {
            return ['code' => 0, 'msg' => '验证码已过期'];
        }
        if ($smsData['phone'] != $phone) {
            return ['code' => 0, 'msg' => '手机号错误'];
        }
        if ($smsData['code'] != $code) {
            return ['code' => 0, 'msg' => '验证码错误'];
        }
        Cache::forget($sms_key);
        return ['code' => 200, 'msg' => 'success'];
    }
}
/**
 * 图片加域名
 */
if (!function_exists('imageurl')) {
    function imageurl($image = '')
    {
        if ($image) {
            $image = env('APP_URL') . '/storage/' . $image;
        }
        return $image;
    }
}
/**
 * 合并图片
 */
if (!function_exists('hebingimage')) {
    function hebingimage($code)
    {
        $path_1 = './background.png';
        $path_2 = './qrcode/' . $code . '.png';

        //创建图片对象
        $image_1 = imagecreatefrompng($path_1);
        $image_2 = imagecreatefrompng($path_2);
        //合成图片
        //imagecopymerge ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h , int $pct )---拷贝并合并图像的一部分
        //将 src_im 图像中坐标从 src_x，src_y 开始，宽度为 src_w，高度为 src_h 的一部分拷贝到 dst_im 图像中坐标为 dst_x 和 dst_y 的位置上。两图像将根据 pct 来决定合并程度，其值范围从 0 到 100。当 pct = 0 时，实际上什么也没做，当为 100 时对于调色板图像本函数和 imagecopy() 完全一样，它对真彩色图像实现了 alpha 透明。
        $image = imagecopymerge($image_1, $image_2, 50, 300, 0, 0, imagesx($image_2), imagesy($image_2), 100);
        // 输出合成图片
        $merge = './hb/' . $code . '.png';
        // var_dump(imagepng($image_1,'./merge.png'));//bool(true)
        $image = imagepng($image_1, $merge);
        return $merge;
    }
}

/**
 * 腾讯云三要素
 */
if (!function_exists('tencentauth')) {
    function tencentauth($id_card, $mobile, $realname)
    {
        try {

            // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
            $cred = new Credential("AKID52qSsBJ90HqlgmsvmNlLj0ANYWHofoob", "jLQLBpcOHyTmsmmfbMuMaaPh147Slvvn");
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("faceid.tencentcloudapi.com");

            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            $client = new FaceidClient($cred, "", $clientProfile);

            // 实例化一个请求对象,每个接口都会对应一个request对象
            $req = new PhoneVerificationRequest();

            $params = array(
                "IdCard" => $id_card,
                "Name" => $realname,
                "Phone" => $mobile
            );
            $req->fromJsonString(json_encode($params));

            // 返回的resp是一个PhoneVerificationResponse的实例，与请求对象对应
            $resp = $client->PhoneVerification($req);
            //            dd($resp);
            return $resp;
            // 输出json格式的字符串回包
            //            print_r($resp->toJsonString());
        } catch (TencentCloudSDKException $e) {
            echo $e;
        }
    }
}

//是否已认证
if (!function_exists('is_certification')) {
    function is_certification($uid)
    {
        $info = Certification::where('uid', $uid)->where('state', 1)->first();
        if ($info) {
            return true;
        } else {
            return false;
        }
    }
}

//获取用户资料
if (!function_exists('getUserInfo')) {
    function getUserInfo($uid)
    {

        $info = User::where('id', $uid)->first();
        return $info;
    }
}




//计算距离
if (!function_exists('GetDistance')) {
    function GetDistance($lat1, $lng1, $lat2, $lng2, $len_type = 1, $decimal = 2)
    {
        $PI = 3.1415926535898;
        $EARTH_RADIUS = 6378.137;
        $radLat1 = $lat1 * $PI / 180.0;
        $radLat2 = $lat2 * $PI / 180.0;
        $a = $radLat1 - $radLat2;
        $b = ($lng1 * $PI / 180.0) - ($lng2 * $PI / 180.0);
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
        $s = $s * $EARTH_RADIUS;
        $s = round($s * 1000);
        if ($len_type > 1) {
            $s /= 1000;
        }
        return round($s, $decimal) / 1000;
    }
}

/* 获取订单号 */
if (!function_exists('getOrderno')) {
    function getOrderno($uid)
    {
        $orderid = '00' . $uid . time();
        return $orderid;
    }
}

/* 生成随机核销码 */
if (!function_exists('generateInviteCode')) {
    function generateInviteCode($length)
    {
        // $verification_code = Str::random($length);
        $verification_code = range(100000,999999);
        $exist = FareOrder::where('verification_code', $verification_code)->exists();
        if ($exist) {
            $verification_code = range(100000,999999);
        }
        return $verification_code;
    }
}

/* 生成随机核销码 */
if (!function_exists('random')) {
    	/* 随机数 */
	function random($length = 6 , $numeric = 0) {
		PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
		if($numeric) {
			$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
		} else {
			$hash = '';
			$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
			$max = strlen($chars) - 1;
			for($i = 0; $i < $length; $i++) {
				$hash .= $chars[mt_rand(0, $max)];
			}
		}
		return $hash;
	}
}

/**
 * 生成usersig
 */
if (!function_exists('getUserSig')) {
    function getUserSig($uid)
    {
        $uid = 'pdd_' . $uid;
        $api = new TLSSigAPIv2(20003573, '93974ed24f6e933bb315a0a138ccefb4c72cae02a3a5d4552c2c06068d742c9b');
        $sig = $api->genSig($uid);
        return $sig;
    }
}

/**
 * 管理员生成usersig
 */
if (!function_exists('genAdminSign')) {
    function genAdminSign()
    {
        $api = new TLSSigAPIv2(20003573, '93974ed24f6e933bb315a0a138ccefb4c72cae02a3a5d4552c2c06068d742c9b');
        $sig = $api->genSig('administrator');
        return $sig;
    }
}
/**
 * 修改im头像和昵称
 */
if (!function_exists('portrait_set')) {
    function portrait_set($uid, $nickname, $avatar)
    {
        $api = new TencentIm();
        $res = $api->portrait_set($uid, $nickname, $avatar);
        return $res;
    }
}

/**
 * 发送订单通知
 */
if (!function_exists('sendImMsg')) {
    function sendImMsg($uid, $concent, $type)
    {
        $api = new TencentIm();
        $res = $api->sendIm($uid, $concent, $type);
        return $res;
    }
}

/**
 * 发送系统通知
 */
if (!function_exists('system_notice')) {
    function system_notice($concent)
    {
        $api = new TencentIm();
        $res = $api->system_notice($concent);
        return $res;
    }
}

/**
 * 增加群成员
 */
if (!function_exists('join_Group')) {
    function join_Group($user_id)
    {
        $api = new TencentIm();
        $res = $api->join_Group($user_id);
        return $res;
    }
}

/**
 * 拉取单聊历史消息
 */
if (!function_exists('admin_getroammsg')) {
    function admin_getroammsg($uid1,$uid2)
    {
        $api = new TencentIm();
        $res = $api->admin_getroammsg($uid1,$uid2);
        return $res;
    }
}

/**
 * 续拉拉取单聊历史消息
 */
if (!function_exists('xu_admin_getroammsg')) {
    function xu_admin_getroammsg($uid1,$uid2,$LastMsgTime,$LastMsgKey)
    {
        $api = new TencentIm();
        $res = $api->xu_admin_getroammsg($uid1,$uid2,$LastMsgTime,$LastMsgKey);
        return $res;
    }
}

/**
 * 判断是否为合法的身份证号码
 */
if (!function_exists('isCreditNo')) {
    function isCreditNo($vStr)
    {


        $vCity = array(
            '11', '12', '13', '14', '15', '21', '22',
            '23', '31', '32', '33', '34', '35', '36',
            '37', '41', '42', '43', '44', '45', '46',
            '50', '51', '52', '53', '54', '61', '62',
            '63', '64', '65', '71', '81', '82', '91'
        );

        if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) {
            return false;
        }

        if (!in_array(substr($vStr, 0, 2), $vCity)) {
            return false;
        }

        $vStr = preg_replace('/[xX]$/i', 'a', $vStr);
        $vLength = strlen($vStr);

        if ($vLength == 18) {
            $vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
        } else {
            $vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
        }

        if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) {
            return false;
        }

        if ($vLength == 18) {
            $vSum = 0;
            for ($i = 17; $i >= 0; $i--) {
                $vSubStr = substr($vStr, 17 - $i, 1);
                $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr, 11));
            }
            if ($vSum % 11 != 1) {
                return false;
            }
        }

        return true;
    }

    /* 时间差计算 */
    function datetime($time)
    {
        $time = strtotime($time);
        $cha = time() - $time;
        $iz = floor($cha / 60);
        $hz = floor($iz / 60);
        $dz = floor($hz / 24);
        /* 秒 */
        $s = $cha % 60;
        /* 分 */
        $i = floor($iz % 60);
        /* 时 */
        $h = floor($hz / 24);
        /* 天 */

        if ($cha < 60) {
            return $cha . '秒前';
        } else if ($iz < 60) {
            return $iz . '分钟前';
        } else if ($hz < 24) {
            return $hz . '小时前';
        } else if ($dz < 30) {
            return $dz . '天前';
        } else {
            return date("Y-m-d", $time);
        }
    }
    /* 密码检查 */
    function passcheck($user_pass)
    {
        /* 必须包含字母、数字 */
        $preg = '/^(?=.*[A-Za-z])(?=.*[0-9])[a-zA-Z0-9~!@&%#_]{6,20}$/';
        $isok = preg_match($preg, $user_pass);
        if ($isok) {
            return 1;
        }
        return 0;
    }

    /* 检验手机号 */
    // function checkMobile($mobile)
    // {
    //     $ismobile = preg_match('#^(\+886)[69]\d{7}$#', $mobile);
    //     if ($ismobile) {
    //         return 1;
    //     }
    //     return 0;
    // }

        /* 检验手机号 */
    function checkMobile($mobile)
    {

        return 1;
        $ismobile = preg_match('/^(0[0-9]*)$/', $mobile);
        if (!$ismobile) {
            return 0;
        }

        if(strlen($mobile) < 10){
            return 0;
        }
        return 1;
    }

    /* 获取用户VIP */
    function getUserVip($uid)
    {
        $rs = array(
            'type' => '0',
        );
        $nowtime = Carbon::now();
        $isexist = VipUser::where('uid', $uid)->first();

        if ($isexist) {
            if ($isexist->endtime <= $nowtime) {
                return $rs;
            }
            $rs['type'] = '1';
        }

        return $rs;
    }

    /* 用户邀请分销 */
    function user_agent_reward($uid, $price)
    {
        $fee = getSetting('invite_bili');

        $agent_profit = round($price * $fee / 100, 2);

        $user = User::where('id', $uid)->select('pid')->first();
        if ($user->pid) {
            $pid_user =  User::where('id', $user->pid)->first();
            if ($pid_user) {
                $pid_user->votes += $agent_profit;
                $pid_user->save();

                //邀请收入记录
                $record = [];
                $record['uid'] = $user->pid;
                $record['fromid'] = $uid;
                $record['money_type'] = 4;
                $record['money'] = $agent_profit;
                $record['action'] = 4;

                DB::transaction(function () use ($record) {
                    IncomeRecord::create($record);
                });

                //邀请收入记录
                $map = [];
                $map['uid'] = $user->pid;
                $map['fromid'] = $uid;
                $map['profit'] = $agent_profit;
                DB::transaction(function () use ($map) {
                    AgentProfit::create($map);
                });
                logger("用户".$user->pid.",收到".$uid."分销收益".$agent_profit);
            }
        }
        return $agent_profit;
    }

    /* 邀请分销 */
    function agent_reward($uid, $price,$orderid)
    {
        $agent_profit = 0;
        logger("分销收益开始");
        $user = User::where('id', $uid)->select('pid')->first();
        if ($user->pid) {
            logger("分销用户".$user->pid);
            //查询陪玩上级经纪人的等级
            $Broker_level = Broker::where('uid',$user->pid)->first();
            logger("分销等级".$Broker_level->level);
            if($Broker_level){
                //查询该等级的抽成比例
                $level_bili = BrokerLevel::where('scale',$Broker_level->level)->first();
                logger("分销等级比例".$level_bili->bili);
                if($level_bili){
                    $agent_profit = round($price * $level_bili->bili / 100, 2);
                }

            }
            logger("分销收益".$agent_profit);
            if($agent_profit>0){
                $pid_user =  User::where('id', $user->pid)->first();
                if ($pid_user) {
                    $pid_user->votes += $agent_profit;
                    $pid_user->save();

                    //邀请收入记录
                    $record = [];
                    $record['uid'] = $user->pid;
                    $record['fromid'] = $uid;
                    $record['money_type'] = 4;
                    $record['money'] = $agent_profit;
                    $record['action'] = 4;

                    DB::transaction(function () use ($record) {
                        IncomeRecord::create($record);
                    });

                    //邀请收入记录
                    $map = [];
                    $map['uid'] = $user->pid;
                    $map['fromid'] = $uid;
                    $map['profit'] = $agent_profit;
                    $map['orderid'] = $orderid;
                    DB::transaction(function () use ($map) {
                        AgentProfit::create($map);
                    });
                    logger("用户".$user->pid.",收到".$uid."分销收益".$agent_profit);
            }


            }
        }
        return $agent_profit;
    }

    function get_agent_reward($uid, $price)
    {
        $agent_profit = 0;
        logger("分销收益开始");
        $user = User::where('id', $uid)->select('pid')->first();
        if ($user->pid) {
            logger("分销用户".$user->pid);
            //查询陪玩上级经纪人的等级
            $Broker_level = Broker::where('uid',$user->pid)->first();
            logger("分销等级".$Broker_level->level);
            if($Broker_level){
                //查询该等级的抽成比例
                $level_bili = BrokerLevel::where('scale',$Broker_level->level)->first();
                logger("分销等级比例".$level_bili->bili);
                if($level_bili){
                    $agent_profit = round($price * $level_bili->bili / 100, 2);
                }
            }
        }
        return $agent_profit;
    }



    /* 判断是否关注 */
	function is_attention($uid,$touid){

	    $is_attention = 0;
		$Attention = Attention::where('uid', $uid)->where('touid', $touid)->first();
		if($Attention){
		    $is_attention = 1;
		}

        return $is_attention;
    }

    function send_sms($phone,$content)
    {
        $checkMobile = checkMobile($phone);
        if(!$checkMobile){
            return ['code' => 0, 'msg' => '手機號格式錯誤！'];
        }
        try {
            $curl = curl_init();
            // url
            $url = 'https://smsb2c.mitake.com.tw/b2c/mtk/SmSend?';
            $url .= 'CharsetURL=UTF-8';
            // parameters
            $data = 'username=83015140SMS';
            $data .= '&password=Gn83015140';
            $data .= "&dstaddr=" . $phone . "";
            $data .= "&smbody=".$content;



            $curl=curl_init();
    		curl_setopt($curl,CURLOPT_URL, $url);
    		curl_setopt($curl,CURLOPT_HEADER, 0);
    		curl_setopt($curl,CURLOPT_HTTPHEADER, array("Content-type: application/x-www-form-urlencoded")
            );
    		curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);
    		curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,0);
    		curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);
    		curl_setopt($curl,CURLOPT_POST, 1);
    		curl_setopt($curl,CURLOPT_POSTFIELDS, $data);
    		$data = curl_exec($curl);
    		logger("短信通知".$data);
    		curl_close($curl);

        } catch (\Exception $e) {
            errorLog(0, '短信发送失败', $e->getLine() . '=>' . $e->getMessage());
            return response()->json([
                'code' => 0,
                'msg' => '短信发送失败',
            ]);
        }

        return response()->json([
            'code' => 200,
            'msg' => '發送成功',
        ]);
    }

    /* curl POST 请求 */
    function curl_post($url, $curlPost = '')
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_POST, true);
        if ($curlPost) {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        }

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在

        $return_str = curl_exec($curl);
        curl_close($curl);
        // dd($return_str);
        return $return_str;
    }
    //经纪人等级晋升
    function broker_up($uid){

        $broker_info = Broker::where('uid',$uid)->first();
        if($broker_info){
            $level1 = BrokerLevel::where('agent_num','<',$broker_info->num)->where('condition', '=', 2)->orderBy('scale', 'desc')->first();
            $level2 = BrokerLevel::where('performance','<',$broker_info->performance)->where('condition', '=', 1)->orderBy('scale', 'desc')->first();
            $level = $level1->sacle >=  $level2->sacel ? $level1 : $level2;
            if($level){
                if($level->scale > $broker_info->level){
                    $broker_info->level = $level->scale;
                    $broker_info->save();
                }
            }

        }
    }

    //会员等级晋升
    function level_up($uid){

        $user_info = User::where('id',$uid)->first();
        if($user_info){
            logger('用戶消費次數'.$user_info->use_num);
            logger('用戶等級'.$user_info->level);
            $level = Level::where('level_up','<=',$user_info->use_num)->orderBy('levelid', 'desc')->first();
            if($level){
                if($level->levelid > $user_info->level){
                    $user_info->level = $level->levelid;
                    $user_info->save();
                }
            }

        }
    }
}
